package com.zqyl.docmanager.service;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;
import java.io.*;

@Service
public class HtmlConverterService {

    /**
     * Convert a document file to HTML format
     * @param filePath path to the document file
     * @return HTML string representation of the document
     */
    public String convertToHtml(String filePath) throws IOException {
        File file = new File(filePath);
        String fileName = file.getName().toLowerCase();
        
        if (fileName.endsWith(".pdf")) {
            return convertPdfToHtml(file);
        } else if (fileName.endsWith(".docx") || fileName.endsWith(".doc")) {
            return convertWordToHtml(file);
        } else {
            throw new IllegalArgumentException("Unsupported file format");
        }
    }

    private String convertPdfToHtml(File file) throws IOException {
        try (PDDocument document = PDDocument.load(file)) {
            PDFTextStripper stripper = new PDFTextStripper();
            String text = stripper.getText(document);
            return convertTextToHtml(text);
        }
    }

    private String convertWordToHtml(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file);
             XWPFDocument document = new XWPFDocument(fis)) {
            
            StringBuilder html = new StringBuilder();
            html.append("<div class='document'>");

            // Process paragraphs
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                processParagraph(paragraph, html);
            }

            // Process tables
            for (XWPFTable table : document.getTables()) {
                processTable(table, html);
            }

            html.append("</div>");
            return html.toString();
        }
    }

    private void processParagraph(XWPFParagraph paragraph, StringBuilder html) {
        if (paragraph.getText().trim().isEmpty()) {
            html.append("<p>&nbsp;</p>");
            return;
        }

        String style = paragraph.getStyle();
        if (style != null && style.startsWith("Heading")) {
            int level = Character.getNumericValue(style.charAt("Heading".length()));
            html.append("<h").append(level).append(">");
            processRuns(paragraph, html);
            html.append("</h").append(level).append(">");
        } else {
            html.append("<p>");
            processRuns(paragraph, html);
            html.append("</p>");
        }
    }

    private void processRuns(XWPFParagraph paragraph, StringBuilder html) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            if (text == null) continue;

            text = text.replace("<", "&lt;").replace(">", "&gt;");

            if (run.isBold() && run.isItalic()) {
                html.append("<strong><em>").append(text).append("</em></strong>");
            } else if (run.isBold()) {
                html.append("<strong>").append(text).append("</strong>");
            } else if (run.isItalic()) {
                html.append("<em>").append(text).append("</em>");
            } else {
                html.append(text);
            }
        }
    }

    private void processTable(XWPFTable table, StringBuilder html) {
        html.append("<table class='border-collapse border'>");
        
        boolean isFirstRow = true;
        for (XWPFTableRow row : table.getRows()) {
            html.append("<tr>");
            
            for (XWPFTableCell cell : row.getTableCells()) {
                String tag = isFirstRow ? "th" : "td";
                html.append("<").append(tag).append(" class='border p-2'>");
                
                for (XWPFParagraph paragraph : cell.getParagraphs()) {
                    processRuns(paragraph, html);
                }
                
                html.append("</").append(tag).append(">");
            }
            
            html.append("</tr>");
            isFirstRow = false;
        }
        
        html.append("</table>");
    }

    private String convertTextToHtml(String text) {
        StringBuilder html = new StringBuilder();
        html.append("<div class='document'>");

        String[] lines = text.split("\n");
        boolean inParagraph = false;

        for (String line : lines) {
            line = line.trim();
            
            if (line.isEmpty()) {
                if (inParagraph) {
                    html.append("</p>");
                    inParagraph = false;
                }
                continue;
            }

            // Check for potential headers
            if (line.matches("^\\d+(\\.\\d+)*\\s+.*")) {
                if (inParagraph) {
                    html.append("</p>");
                    inParagraph = false;
                }
                html.append("<h2>").append(line).append("</h2>");
            } else {
                if (!inParagraph) {
                    html.append("<p>");
                    inParagraph = true;
                } else {
                    html.append(" ");
                }
                html.append(line.replace("<", "&lt;").replace(">", "&gt;"));
            }
        }

        if (inParagraph) {
            html.append("</p>");
        }

        html.append("</div>");
        return html.toString();
    }
} 